package com.english.utils;

import com.english.config.WechatConfig;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信工具类
 * 处理微信小程序API调用
 * 
 * @author sqh
 * @since 2025-01-15
 */
@Component
public class WechatUtil {

    @Autowired
    private WechatConfig wechatConfig;
    
    private final WebClient webClient = WebClient.create();
    private final ObjectMapper objectMapper = new ObjectMapper();

    /**
     * 通过code获取微信openid和session_key
     * @param code 微信授权码
     * @return 包含openid和session_key的Map
     */
    public Map<String, String> getWechatSession(String code) {
        try {
            // 验证参数
            if (code == null || code.trim().isEmpty()) {
                System.err.println("微信授权码为空");
                return null;
            }
            
            if (wechatConfig.getAppid() == null || wechatConfig.getAppid().trim().isEmpty()) {
                System.err.println("微信appid未配置");
                return null;
            }
            
            if (wechatConfig.getSecret() == null || wechatConfig.getSecret().trim().isEmpty()) {
                System.err.println("微信secret未配置");
                return null;
            }
            
            String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                wechatConfig.getAppid(), wechatConfig.getSecret(), code
            );
            
            System.out.println("调用微信API，appid: " + wechatConfig.getAppid());
            System.out.println("微信授权码: " + code);
            
            String response = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();
            
            if (response != null) {
                System.out.println("微信API响应: " + response);
                JsonNode jsonNode = objectMapper.readTree(response);
                
                // 检查是否有错误
                if (jsonNode.has("errcode") && jsonNode.get("errcode").asInt() != 0) {
                    int errcode = jsonNode.get("errcode").asInt();
                    String errmsg = jsonNode.get("errmsg").asText();
                    System.err.println("微信API错误: " + response);
                    System.err.println("错误代码: " + errcode + ", 错误信息: " + errmsg);
                    
                    // 根据错误代码提供更详细的错误信息
                    switch (errcode) {
                        case 40029:
                            System.err.println("错误原因: 授权码无效，可能原因：1) 授权码已使用 2) 授权码已过期 3) appid与授权码不匹配");
                            break;
                        case 40163:
                            System.err.println("错误原因: 授权码已被使用，请重新获取授权码");
                            throw new RuntimeException("40163: 授权码已被使用，请重新获取授权码");
                        case 45011:
                            System.err.println("错误原因: 频率限制，请稍后重试");
                            break;
                        case 40013:
                            System.err.println("错误原因: appid无效");
                            break;
                        case 40002:
                            System.err.println("错误原因: secret无效");
                            break;
                        default:
                            System.err.println("未知错误代码: " + errcode);
                    }
                    return null;
                }
                
                // 返回openid和session_key
                Map<String, String> result = new HashMap<>();
                result.put("openid", jsonNode.get("openid").asText());
                result.put("session_key", jsonNode.get("session_key").asText());
                System.out.println("微信API调用成功，openid: " + result.get("openid"));
                return result;
            }
            
            return null;
            
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("调用微信API异常: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取微信access_token
     * @return access_token
     */
    public String getAccessToken() {
        try {
            String url = String.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                wechatConfig.getAppid(), wechatConfig.getSecret()
            );
            
            String response = webClient.get()
                    .uri(url)
                    .retrieve()
                    .bodyToMono(String.class)
                    .block();
            
            if (response != null) {
                JsonNode jsonNode = objectMapper.readTree(response);
                
                if (jsonNode.has("access_token")) {
                    return jsonNode.get("access_token").asText();
                }
            }
            
            return null;
            
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
} 